package com.itheima.itheima_health.controller.user;

import com.itheima.itheima_health.constant.EmailConstant;
import com.itheima.itheima_health.constant.MessageConstant;
import com.itheima.itheima_health.constant.RedisConstant;
import com.itheima.itheima_health.entity.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * 邮箱发送相关代码
 */
@RestController
@RequestMapping("/user/email")
@Slf4j
@Api(tags = "邮箱发送相关接口")
public class EmailController {
    //存储随机生成的校验码
    private String cdoe_store = null;
    @Autowired(required = false)
    // 引入Spring Mail依赖后，会自动装配到IOC容器
    private JavaMailSender sender;
    @Autowired
    private RedisTemplate redisTemplate;
    @PostMapping("/send")
    @ApiOperation("邮箱发送")
    public Result sendEmail(String email){
        String code = (Math.random() + "").substring(2, 8);	//生成6位随机数
        cdoe_store = code;
        //String email = EmailConstant.RECEIVER_EMAIL;	//你想发给哪个邮箱
        SimpleMailMessage message = new SimpleMailMessage();
        message.setSubject("悦生健康验证码"); // 发送邮件的主题
        message.setText("您好，您正在操作敏感信息，需要核验您的身份,您收到的验证码为:" + code); // 邮件的内容
        message.setTo(email); // 指定要接收邮件的用户邮箱账号
        message.setFrom(EmailConstant.SENDER_EMAIL); // 邮件发送方，也就是配置文件中的邮件地址。
        sender.send(message); // 调用send方法发送邮件

        //缓存验证码到redis
        redisTemplate.opsForSet().add(email+RedisConstant.EMAIL_CODE_KEY,code);
        //设置验证码过期时间
        redisTemplate.expire(email + RedisConstant.EMAIL_CODE_KEY, 2, TimeUnit.MINUTES);

        log.info("验证码发送成功发送至{}",email);
        return new Result(true, MessageConstant.EMAIL_VERIFY_SUCCESS,code);
    }
}
